using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    public enum ELanguage { ZH_CN, EN_US, PT_BR, VI_VN }

    public struct Event_LanguageChange
    {
    }

    public class I18N : MonoBehaviour
    {
        [Serializable]
        public class Node
        {
            public GameObject go;
            public Text text;
            public List<string> indexLanguages;
            public Node(GameObject go)
            {
                this.go = go;
                int langCount = Enum.GetValues(typeof(ELanguage)).Length;
                indexLanguages = new List<string>();
                for (int i = 0; i < langCount; i++) indexLanguages.Add("");
            }
        }

        [Serializable]
        public class KeyContent
        {
            public List<string> languages = new List<string>();
            public KeyContent()
            {
                int langCount = Enum.GetValues(typeof(ELanguage)).Length;
                languages = new List<string>();
                for (int i = 0; i < langCount; i++) languages.Add("");
            }
        }

        public ELanguage language = ELanguage.ZH_CN;
        //当前语言
        public static I18NConfig config { get; private set; }
        public List<Node> nodes = new List<Node>();
        public List<string> keys = new List<string>();
        public Text newText;
        public List<KeyContent> keyContents = new List<KeyContent>();

        private static event Action languageChangeAction;
        private static ELanguage currLanguage;
        private static bool hasReadCache;
        private string goName;

        public static ELanguage CurrLanguage
        {
            get
            {
                if (!hasReadCache)
                {
                    int cache = PlayerPrefs.GetInt("Language", -1);
                    if (cache >= 0)
                    {
                        currLanguage = (ELanguage)cache;
                    }
                    else
                    {
                        //如果没有缓存，默认语言看发布哪个国家
                        switch (CGFConfig.Instance.ReleaseArea)
                        {
                            case EArea.Common:
                            case EArea.India:
                                currLanguage = ELanguage.EN_US;
                                break;
                            case EArea.China:
                            default:
                                currLanguage = ELanguage.ZH_CN;
                                break;
                            case EArea.Brazil:
                                currLanguage = ELanguage.PT_BR;
                                break;
                            case EArea.Vietnam:
                                currLanguage = ELanguage.VI_VN;
                                break;
                        }
                    }
                    hasReadCache = true;
                }
                return currLanguage;
            }
            set
            {
                currLanguage = value;
                PlayerPrefs.SetInt("Language", (int)value);
                languageChangeAction?.Invoke();
                EventManager.Emit(new Event_LanguageChange());
            }
        }

        public static async void Init()
        {
            TextAsset asset = await ResManager.Instance.LoadAsset<TextAsset>($"{Define.ConfigFolder}/{Define.I18NAbName}");
            config = I18NConfig.Parse(asset.text);
            UnityEngine.Debug.Log("当前语言：" + CurrLanguage);
        }

        public void OnDestroy()
        {
            languageChangeAction -= RefreshLanguage;
        }

        public void Awake()
        {
            if (config == null)
            {
                UnityEngine.Debug.LogError("请在HitfixLaunch.cs脚本中，取消注释 I18N.Init()");
            }
            goName = name.Replace("(Clone)", "");
            RefreshLanguage();
            languageChangeAction += RefreshLanguage;
        }

        void RefreshLanguage()
        {
            int langIndex = (int)CurrLanguage;
            if (Application.isPlaying && config != null)
            {
                //运行时读配表
                if (config.prefabConfigs.ContainsKey(goName))
                {
                    I18NConfig.PrefabConfig prefabConfig = config.prefabConfigs[goName];
                    for (int i = 0; i < prefabConfig.indexContents.Count; i++)
                    {
                        Node node = nodes[i];
                        List<string> nodeLanguages = prefabConfig.indexContents[i];
                        if (langIndex < nodeLanguages.Count)
                        {
                            if (!node.text) node.text = node.go.GetComponent<Text>();
                            node.text.text = StringHelper.SurportSpace(nodeLanguages[langIndex]);
                        }
                    }
                }
            }
            else
            {
                //非运行时读预置体本身记录
                for (int i = 0; i < nodes.Count; i++)
                {
                    Node node = nodes[i];
                    if (langIndex < node.indexLanguages.Count && node.text)
                    {
                        if (!node.text) node.text = node.go.GetComponent<Text>();
                        node.text.text = StringHelper.SurportSpace(node.indexLanguages[langIndex]);
                    }
                }
            }
        }

        //外部调用///////////////////////
        public static string GetLanguageName(ELanguage language)
        {
            switch (language)
            {
                case ELanguage.EN_US: return "English(US)";
                case ELanguage.PT_BR: return "Português(Brasil)";
                case ELanguage.VI_VN: return "Tiếng Việt";
                case ELanguage.ZH_CN: return "简体中文";
            }
            return null;
        }

        /// <summary>
        /// 获取自定义Key的翻译
        /// </summary>
        public string GetTextByKey(string key)
        {
            int index = 0;
            for (int i = 0; i < keys.Count; i++)
            {
                if (keys[i].Equals(key))
                {
                    index = i;
                    break;
                }
            }
            if (Application.isPlaying && config != null)
            {
                //运行时读配表
                if (config.prefabConfigs.ContainsKey(goName))
                {
                    I18NConfig.PrefabConfig prefabConfig = config.prefabConfigs[goName];
                    if (index < prefabConfig.keyContents.Count)
                    {
                        return StringHelper.SurportSpace(prefabConfig.keyContents[index][(int)CurrLanguage]);
                    }
                }
                else
                {
                    Debug.LogError($"Config/i18n.txt配置里不存在{goName}的配置");
                }
            }
            else
            {
                //非运行时读预置体本身记录
                if (index < keyContents.Count)
                {
                    return StringHelper.SurportSpace(keyContents[index].languages[(int)CurrLanguage]);
                }
            }
            return "";
        }

        public static string Currency
        {
            get
            {
                switch (CGFConfig.Instance.ReleaseArea)
                {
                    case EArea.Common:
                        return "$";
                    case EArea.Brazil:
                        return "R$";
                    case EArea.India:
                        return "₹";
                    case EArea.Vietnam:
                        return "₫";
                    case EArea.China:
                    default:
                        return "￥";
                }
            }
        }

        public static string MonthDayFormat
        {
            get
            {
                switch (CurrLanguage)
                {
                    case ELanguage.ZH_CN:
                        return "MM/dd";
                    default:
                        return "dd/MM";
                }
            }
        }

        //自动判断补全国际码
        public static string CheckPhoneAddPrefix(string phoneNum)
        {
            string prefix = PhoneNumPrefix;
            if (!phoneNum.StartsWith(prefix))
            {
                return prefix + phoneNum;
            }
            return phoneNum;
        }

        public static string PhoneNumPrefix
        {
            get
            {
                switch (CGFConfig.Instance.ReleaseArea)
                {
                    case EArea.Common:
                        return "";
                    case EArea.Brazil:
                        return "+55";
                    case EArea.India:
                        return "+99";
                    case EArea.Vietnam:
                        return "+84";
                    case EArea.China:
                    default:
                        return "+86";
                }
            }
        }
    }

    //扩展GameObject和Transform方法，方便读取Reference里的Node
    public static class I18NExtand
    {
        public static string GetLangByKey(this Transform trans, string key)
        {
            return trans.gameObject.GetLangByKey(key);
        }

        public static string GetLangByKey(this GameObject go, string key)
        {
            I18N i18N = go.GetComponent<I18N>();
            if (!i18N)
            {
                Debug.LogError($"{go.name}未绑定 I18N 组件");
                return "";
            }
            return i18N.GetTextByKey(key);
        }
    }
}
